const { Router } = require("express");
const { body, validationResult } = require("express-validator");
const MD5 = require("md5");
const User = require('../model/user');
// 路由中间件通过后的操作api
const authCtrl = require("../controllers/authCtrl");
const auth = require("../middleware/auth");

const router = new Router();

// 添加管理员账号
(async () => {
  const user = await User.findOne({ username: "root" });
  if (!user) {
    await User.create({
      username: "root",
      password: MD5("123456"),
      tel: "12345678991",
      isAdmin: true,
      avatar: "http://127.0.0.1:8088/default-avatar.jpg"
    }, {
      username: '123',
      password: MD5("123"),
      tel: "17820099999",
      isAdmin: false,
      avatar: "http://127.0.0.1:8088/default-avatar2.jpg"

    });
  }
})();


/* 
登录请求：/api/auth/login
method: post
body参数：username, password
*/
router.post(
  "/login",
  body("username").notEmpty().isString(), //验证body.username参数不为空
  body("password").notEmpty().isString(), //验证body.password参数不为空
  (req, res, next) => {
    console.log('123', req.body);

    //获取验证的结果
    const result = validationResult(req);
    if (result.isEmpty()) {
      //参数没有问题
      next();
    } else {
      //参数缺少了,参数格式不正确
      res.status(400).json({ message: "缺少参数或参数格式不正确" });
    }
  },
  authCtrl.login
);

/* 
验证登录：/api/auth/check_login
method: get
headers: {
  authorization: token
}
*/
router.get("/check_login", auth, authCtrl.checkLogin);




let multer = require('multer');
let path = require('path');
const { request } = require("http");

let storage = multer.diskStorage({
  // // 设置图片存储路径
  destination: path.join(__dirname, '../static'),

  // // 设置图片存储时的名字
  filename: function (req, file, cb) {

    let ext = path.extname(file.originalname)

    let userid = req.userInfo._id.toString()

    let filename = file.fieldname + '-' + userid + ext
    cb(null, filename)
  }

})
let upload = multer({ storage: storage })


/**
 * 修改个人信息 /api/auth/changedata
 * post
 * 
 */
//   (req, res, next) => {
//   // 执行一些操作以获取 req.body 的内容
//   // ...
//   console.log('req', req.body);

//   // 继续传递请求到 upload.single('avatar')
//   next();
// },
router.post('/changedata', auth, upload.single('avatar'), authCtrl.changedata)

module.exports = router;
